using System;
using MyMessages;
using NServiceBus;

namespace MyPublisher
{
    public class MessagePublisher : IWantToRunAtStartup
    {
        public IBus Bus { get; set; }

        /*public void Run()
        {
            Console.WriteLine("This will publish IEvent and EventMessage alternately.");
            Console.WriteLine("Press 'Enter' to publish a message.To exit, Ctrl + C");

            bool publishIEvent = true;
            while (Console.ReadLine() != null)
            {
                var eventMessage = publishIEvent ? Bus.CreateInstance<IEvent>() : new EventMessage();

                eventMessage.EventId = Guid.NewGuid();
                eventMessage.Time = DateTime.Now.Second > 30 ? (DateTime?)DateTime.Now : null;
                eventMessage.Duration = TimeSpan.FromSeconds(99999D);

                Bus.Publish(eventMessage);

                Console.WriteLine("Published event with Id {0}.", eventMessage.EventId);
                Console.WriteLine("==========================================================================");

                publishIEvent = !publishIEvent;

            }
        }*/

        public void Run()
        {
            Console.WriteLine("This will publish Saga messages.");
            Console.WriteLine("Press 'Enter' to publish a message.To exit, Ctrl + C");


            // Publishes a referesh saga message to clear out any tables
            int messageCounter = 0;

            while (Console.ReadLine() != null)
            {
                if(messageCounter == 0)
                {
                    var refreshMessage = new RefreshSagaMessage();
                    Bus.Publish(refreshMessage);
                }

                Console.WriteLine("Publishing Saga Messages.");

                var beginSagaMessage = new BeginSagaMessage() {BeginDate = DateTime.Today, ProcessId = ++messageCounter};
                Bus.Send(beginSagaMessage);
                Console.WriteLine("Published BeginSagaMessage with Id {0}.", beginSagaMessage.ProcessId);

                var continueSagaMessage = new ContinueSagaMessage() { ProcessId = messageCounter, SomeMoreInformation = 1, SomeMoreInformation2 = "Some Contextual Information" };
                Bus.Send(continueSagaMessage);
                Console.WriteLine("Published ContinueSagaMessage with Id {0}.", continueSagaMessage.ProcessId);

                var endSagaMessage = new EndSagaMessage() { CompletionMessage = String.Format("Ending Saga {0}", messageCounter), ProcessId = messageCounter, EndDate = DateTime.Today};
                Bus.Send(endSagaMessage);
                Console.WriteLine("Published EndSagaMessage with Id {0}.", endSagaMessage.ProcessId);
            }
        }


        public void Stop()
        {

        }
    }
}